package com.kma.ncpractice2013.dao;

import com.kma.ncpractice2013.model.UserGroup;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 *
 * @author Illya
 */
public class UserGroupDAO extends DAO<UserGroup>
{


	private static final String SELECT_BY_ID = "SELECT * FROM USER_GROUPS WHERE ID = ?";
    private static final String UPDATE = "UPDATE USER_GROUPS SET NAME = ?, DISCOUNT = ? WHERE ID = ?";

    public void create(UserGroup userGroup)
    {
        String sql = "INSERT INTO USER_GROUPS(NAME,DISCOUNT) VALUES (?,?)";
        jdbcTemplate.update(sql, new Object[]{userGroup.getName(),
            userGroup.getDiscount()});
    }

    public void update(UserGroup userGroup)
    {
        String sql = UPDATE;
        jdbcTemplate.update(sql, new Object[]{userGroup.getName(),userGroup.getDiscount(),userGroup.getId()});
    }

	public UserGroup getById(int id)
    {
        List<UserGroup> userGroupList;
        String sql = SELECT_BY_ID;
        userGroupList = jdbcTemplate.query(sql, new UserGroupRowMapper(), id);
        return userGroupList.get(0);
    }

    public List<UserGroup> getAll()
    {
        String sql = "SELECT * FROM USER_GROUPS ";
	    return jdbcTemplate.query(sql, new UserGroupRowMapper());
    }

    public void deleteById(int id)
    {
        String sql = "DELETE FROM USER_GROUPS WHERE ID = " + id;
        jdbcTemplate.update(sql);
    }
    
    private static final class UserGroupRowMapper implements ParameterizedRowMapper<UserGroup>
    {
        @Override
        public UserGroup mapRow(ResultSet rs, int rowNum) throws SQLException
        {
            UserGroup userGroup = new UserGroup();
            userGroup.setId(rs.getInt("id"));
            userGroup.setName(rs.getString("name"));
            userGroup.setDiscount(rs.getInt("discount"));
	        //userGroup.setCommission(rs.getInt("commission"));
            // set relatedUsers?
            return userGroup;
        }
    }
}
